import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/entity/home/search/match_search_entity.dart';
import 'package:ball_lion/entity/home/search/search_entity.dart';

class SearchLogic extends GetxController with GetTickerProviderStateMixin {
  late List<List<SearchEntity>?> entity =
      List.generate(tabs.length, (index) => null);
  List<SearchEntity>? hot;
  List<MatchSearchItem> hotWord = [];
  bool _goSearch = false;
  String searchWord = "";
  final Rx<String> _str = "".obs;
  final List<String> tabs = [
    "全部",
    if (ModeConfig.expert) "专家",
    if (ModeConfig.expert) "方案",
    "联赛",
    "球队",
    "比赛",
    "资讯"
  ];
  final List<int> tabTYpe = [
    0,
    if (ModeConfig.expert) 1,
    if (ModeConfig.expert) 2,
    3,
    4,
    5,
    6
  ];
  late final List<String> tabStr = List.generate(tabs.length, (index) => "");
  late final TabController tabController =
      TabController(length: tabs.length, vsync: this);
  int _currentIndex = 0;

  String get str => _str.value;
  int get currentIndex => _currentIndex;
  bool get goSearch => _goSearch;

  set goSearch(bool value) {
    _goSearch = value;
    update();
  }

  set currentIndex(int value) {
    _currentIndex = value;
    update();
  }

  set str(String value) {
    _str.value = value;
  }

  bool firstInput = true;
  final textController = TextEditingController();
  late FocusNode focus;

  @override
  void onInit() async {
    tabController.addListener(() {
      if (currentIndex != tabController.index) {
        currentIndex = tabController.index;
        if (tabStr[currentIndex] != str) {
          getSearch();
          tabStr[currentIndex] = str;
          update();
        }
      }
    });
    super.onInit();
  }

  Future getSearch() async {
    if (str.isNotEmpty) {
      entity[currentIndex] =
          await OtherApi.getSearch(type: currentIndex, text: str);
      goSearch = true;
      if (SpUtils.searchHistory == null ||
          SpUtils.searchHistory?.contains(str) == false) {
        SpUtils.setSearchHistory(str);
      }
      searchWord = str;
      update();
    }
  }

  Future getHot() async {
    hot = await OtherApi.getSearch();
    if (hot.hasValue) {
      hotWord = hot
              ?.firstWhere((element) => element.type == 5)
              .list
              ?.map((e) => MatchSearchItem.fromJson(e))
              .toList() ??
          [];
    }
    update();
  }
}
